package com.huarun.shiro;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.PathMatchingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huarun.common.ResponseMessage;
import com.huarun.common.util.Constant;
import com.huarun.common.util.MD5Util;
import com.huarun.common.util.ResultCodeValue;

/**
 * 
 * @author hqy
 * @创建时间   2018-10-24 19:29
 * @Description 针对智慧运营后台公钥判断
 */
public class PCUrlValidateFilter extends PathMatchingFilter {
	private Logger logger = LoggerFactory.getLogger(PCUrlValidateFilter.class);

	@Override
	protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		logger.info("=======PCUrlValidateFilte=======");
		/**是否从智慧运营管理平台请求过来标识*/
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.setCharacterEncoding("UTF-8");
		httpServletResponse.setContentType("application/json; charset=utf-8");
		if (httpServletRequest.getMethod().equals("OPTIONS")) {
			httpServletResponse.setStatus(200);
			return true;
		}
		String headAuth = httpServletRequest.getHeader("Authorization");
		JSONObject headObj = JSONObject.parseObject(headAuth);
		String time = headObj.getString("time") + "";
		String token = headObj.getString("token");

		String secret = Constant.PC_SECRET;
		String appkey = Constant.PC_APPKEY;

		String tokenStr = "appkey=" + appkey + "&time=" + time + secret;
		String nowToken = MD5Util.getMD5(tokenStr, Constant.CHARSET);
		if (!nowToken.equals(token)) {
			PrintWriter writer = null;
			OutputStreamWriter osw = null;
			try {
				osw = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
				writer = new PrintWriter(osw, true);
				writer.write(JSON.toJSONString(
						ResponseMessage.failureMessage(ResultCodeValue.R_PARAM_ERROR, "token验证不通过", null)));
				writer.flush();
			} catch (UnsupportedEncodingException e) {
				logger.error("token验证不通过:拦截器返回信息失败:" + e.getMessage(), e);
			} catch (IOException e) {
				logger.error("token验证不通过:拦截器返回信息失败:" + e.getMessage(), e);
			} finally {
				if (writer != null) {
					writer.close();
				}
				if (osw != null) {
					osw.close();
				}
			}
			return false;
		}
		return true;

	}

}
